/**
 * Created by chengming on 18/5/27.
 * version 1.0
 */
const BaseJsonAdapter = require('../base/BaseJsonAdapter');
const iconv = require("iconv-lite");
const vm = require('vm');
const request = require('request-promise');
const logger = require('../../conf/logger');
const querystring = require("querystring")
const cheerio = require('cheerio');
const urlTool = require('url');

/**
 * 北京互金网
 * @type {module.Bjp2p}
 */
module.exports = class FxStreet extends BaseJsonAdapter {

    async doRequest() {
        var form = {
            "requests": [{
                "indexName": "FxsIndexPro",
                "params": "query=&hitsPerPage=15&maxValuesPerFacet=9&page=0&filters=CultureName%3Aen%20AND%20Category%3A'Crypto'&facets=%5B%22Tags%22%2C%22AuthorName%22%5D&tagFilters="
            }]
        }

        var formData = querystring.stringify(form);
        var contentLength = formData.length;

        var options = {
            // uri:'http://www.bjp2p.com.cn/supervise/queryNews4List',
            uri: this.requestUrl,
            json: form,
            method: "POSt",
            encoding: null
        }
        let body = await request(options)
        return body;
    }


    async reqJson() {
        const body = await this.doRequest();
        // let decodeBody = iconv.decode(body, this.encoding).toString();
        // let obj = JSON.parse(decodeBody);
        // let html = obj.data.article_info;
        //
        // let data = this.parseHtml(html, "li a")
        //
        // console.log("-----decodeBody: " + decodeBody)
        return body;
    }

    parseHtml(html, linkRule) {
        //将解析后的内容加载进解析器
        let $ = cheerio.load(html);

        let contents = [];
        let that = this;
        let rangeText = '';
        $(linkRule).each(function () {

            let title = $(this).text().trim();
            let href = '';
            if ($(this).is('a') && $(this).attr('href')) {
                href = urlTool.resolve(that.requestUrl, $(this).attr('href'));
            }

            if (title.length != 0 || href.length != 0) {
                contents.push({
                    title: title,
                    href: href
                });
                rangeText += title + href;
            }
        });

        return {
            rangeText: rangeText,
            contents: contents
        };
    }
}
